package com.common.www.controller.district;


import org.springframework.boot.base.jpa.domain.PageableRequest;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.Sort;
import com.common.www.bean.entity.district.ProvinceCity;
import com.common.www.bean.vo.ProvinceCityVo;
import com.common.www.service.district.ProvinceCityService;
import com.common.www.utils.R;
import com.common.www.utils.ResultUtil;
import com.common.www.utils.SortUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;


@RestController
@CrossOrigin()
@Api(tags = "API 行政区域相关接口")
@RequestMapping(value = {"/api/district"})
public class ProvinceCityController {

    @Autowired
    ProvinceCityService provinceCityService;

    @ApiOperation("查询省市区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "String"),
            @ApiImplicitParam(name = "level", value = "String"),
    })
    @RequestMapping(value = "/getDistrict", method = RequestMethod.POST)
    public Result getDistrict(Long parentId, Integer level) {
        if (parentId == null && level == null) {
            return R.fail("参数异常");
        }
        HashMap hashMap = new HashMap();
        if (parentId != null) {
            hashMap.put("parent.id", parentId);
        }
        if (level != null) {
            hashMap.put("level", level);
        }

        PageableRequest pageableRequest = new PageableRequest();
        pageableRequest.setSort(SortUtils.addSort(new Sort("sort", "asc")));
        List<ProvinceCity> list = provinceCityService.queryToList(hashMap, pageableRequest);

        List<ProvinceCityVo> voList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ProvinceCityVo vo = new ProvinceCityVo();
            BeanUtils.copyProperties(list.get(i), vo);
            voList.add(vo);
        }
        return ResultUtil.returnSuccess(voList);
    }


}
